<?php
/**
 * KePHP, Keep PHP easy!
 */

namespace CSService\Model\User;

use CSService\Helper\CSCipher;
use Ke\Adm\Model;
use Ke\Utils\Success;
use Ke\Web\Http;
use Ke\Utils\Failure;

/**
 * Class User
 * tableName user
 *
 * // class properties
 * @property int    $id         id
 * @property string $login_id   登录id
 * @property string $password   密码
 * @property string $ws_token   ws令牌
 * @property int    $created_at 创建时间
 * @property int    $updated_at 更新时间
 * // class properties
 */
class User extends Model
{

	protected static $pk = 'id';

	protected static $pkAutoInc = true;

	protected static $columns = [
		'login_id'    => ['label' => '登录账号', 'require' => 1, 'edit' => 'text', 'unique' => 1],
		'password'    => [
			'edit'          => 'password',
			'label'         => '登录密码',
			'min'           => 6,
			'max'           => 128,
			self::ON_CREATE => [
				'require' => 1,
			],
			'hidden'        => 1,
		],
		'cf_password' => [
			'edit'    => 'password',
			'label'   => '确认密码',
			'dummy'   => 1,
			'require' => 1,
			'equal'   => 'password',
		],
		'ws_token'    => [
			'edit'    => 'text',
			'require' => 1,
			'table'   => false,
		],
		'ws_key'      => ['table' => false],
	];

	public static function dbColumns()
	{
		// database columns
		// generated as 2016-02-01 22:52:19
		return [
			'id'         => ['int' => 1, 'pk' => 1, 'autoInc' => 1],
			'login_id'   => ['label' => '登录id', 'max' => 32],
			'password'   => ['label' => '密码', 'max' => 64],
			'ws_token'   => ['label' => 'ws令牌', 'max' => 32],
			'created_at' => ['label' => '创建时间', 'timestamp' => 1, self::ON_CREATE => 'now'],
			'updated_at' => ['label' => '更新时间', 'timestamp' => 1, self::ON_UPDATE => 'now'],
		];
		// database columns
	}

	public static function login(Http $http)
	{
		if (!$http->isPost('login'))
			return new Failure('无效请求或非法来源');
		$errors = [];
		$loginId = $http->getSecurityData('login_id');
		$password = $http->getSecurityData('password');
		if (empty($loginId))
			$errors['login_id'] = '登录账号不能留空！';
		if (empty($password))
			$errors['password'] = '登录密码不能留空！';
		elseif (strlen($password) < 6)
			$errors['password'] = '登录密码最少应为6为字符！';
		if (!empty($errors))
			return new Failure('登录信息不符合要求', $errors);
		/** @var User $user */
		$user = static::query(false)->where('login_id', 'in', $loginId)->findOne();
		if ($user->passwordVerify($password)) {
			$_SESSION['user_id'] = $user->id;
			return new Success('登录成功，欢迎回来！');
		}
		return new Failure('验证失败', ['login_id' => '登录账号或登录密码有误！']);
	}

	public static function logout()
	{
		if (isset($_SESSION['user_id'])) {
			unset($_SESSION['user_id']);
		}
		return true;
	}

	protected function validateSave($process, array &$data)
	{
		if (empty($this->ws_token)) {
			$data['ws_token'] = md5(CSCipher::makeRandKey(16));
		}
	}

	protected function beforeCreate(array &$data)
	{
		$data['password'] = $this->passwordHash($data['password']);
	}

	protected function beforeUpdate(array &$data)
	{
		if (isset($data['password'])) {
			if (empty($data['password']) || $this->passwordVerify($data['password']))
				unset($data['password']);
			else
				$data['password'] = $this->passwordHash($data['password']);
		}
	}

	public function passwordHash(string $password)
	{
		return password_hash($password, PASSWORD_BCRYPT, [
			'cost' => 11,
		]);
	}

	public function passwordVerify(string $inputPassword)
	{
		$inputPassword = trim($inputPassword);
		if (empty($inputPassword) && $this->isNew())
			return false;
		return password_verify($inputPassword, $this->getHiddenData('password'));
	}

	public function getWSToken()
	{
		$cipher = new CSCipher(CS_HANDLE_KEY);
		return $cipher->encrypt($this->ws_token);
	}
}
